<?php
/**
 * 登录控制器
 */
namespace Home\Controller;
use Think\Controller;
use Think\Model;
use Think\Verify;
class LoginController extends Controller
{
    /**
     * 登录页面视图
     */
    public function index () {
        $this->display();
    }

    /**
     * 登录操作处理
     */
   public function login () {
       if (!IS_POST) {
           $this->error("非法请求");
       }

        $name = I('post.username');
        $pwd = md5(I('post.userpwd'));
        $verify = I('post.verify');
        if (!$this->check_verify($verify)) {
            $this -> error('验证码错误，请重试！',U('Login/index','',''));
        }
        $db = M('user');
        $user = $db->where(array('username' => $name))->find();

        if (!user || $user['password'] != $pwd) {
            $this -> error('用户名或者密码错误，请重试！',U('Login/index','',''));
        }
        if ($user['lock']) {
            $this -> error('用户被锁定，无法登录！',U('Login/index','',''));
        }

        $data = array(
            'id' => $user['id'],
            'logintime' => time(),
            'loginip' => get_client_ip()
        );
        $db->save($data);
        session('userid', $user['id']);
        session('loginuser', $user['username']);
        session('logintime', date('Y-m-d H:i', $user['logintime']));
        session('now', date('Y-m-d H:i', time()));
        session('loginip', $user['loginip']);
        session('mysql_version',$this->_mysql_version());
        $result = array("msg" => "登陆成功", "errorCode" => 0);
        $this->success('登录成功，正在为您跳转...',U('Index/Index','',''));
    }

    private function _mysql_version()
    {
        $Model = new Model();
        $version = $Model->query("select version() as ver");
        return $version[0]['ver'];
    }

    /**
     * 检测验证码
     */
    private function check_verify($code, $id = "")
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    /**
     * 获取验证码
     */
    public function verify()
    {
        $Verify = new Verify();
        $Verify->length = 4; // 验证码位数
        $Verify->codeSet = '0123456789';//纯数字验证码
        $Verify->entry();
    }
}
?>